package myJs.user

import myJs.Header
import myJs.Implicits._
import myJs.Utils._
import scala.scalajs.js.Dynamic.{global=>g}
import myJs.myPkg._
import myJs.myPkg.bootstrap.Bootstrap.default._
import myJs.myPkg.jquery._
import myJs.tool.Tool
import myJs.tool.Tool._
import org.scalajs.dom._
import org.scalajs.dom.ext.Ajax
import scalatags.Text.all._

import scala.collection.immutable.SeqMap
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import scala.scalajs.js
import scala.scalajs.js.Date
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}
import scala.scalajs.js.JSConverters._


/**
 * Created by yz on 2019/4/25
 */
@JSExportTopLevel("SignIn")
object SignIn {

  val modalId = "viewModal"
  val tableId = "table"
  val myDate = new Date()
  val monthFirst = {
    new Date(myDate.getFullYear().toInt, myDate.getMonth().toInt, 1).getDay().toInt
  }

  @JSExport("init")
  def init = {
    refreshCalendar
    refreshHasSignIn
    refreshCoin
    initTable
    registerEvent

  }

  def tbFmt(columnName: String): js.Function = (v: js.Any, row: js.Dictionary[js.Any]) => columnName match {
    case _ => v
  }

  def expStyle(columnName: String): js.Function = (v: js.Any, row: js.Dictionary[Any]) => columnName match {
    case _ => v
  }

  def initTable = {
    val map = SeqMap("time" -> messages("signUpDate"), "reward" -> messages("reward"), "explain" -> messages("note"))
    val columnNames = map.keyList
    val columns = columnNames.map { columnName =>
      val title = map.getOrElse(columnName, columnName)
      val fmt = tbFmt(columnName)
      val style = expStyle(columnName)
      val basicOptions = ColumnOptions.field(columnName).title(title).sortable(true).formatter(fmt).cellStyle(style)
      columnName match {
        case x if List("size", "uploadTime", "fileName", "comment", "tags").contains(x) => basicOptions.
          sortable(false).operateable(true)
        case _ => basicOptions
      }
    }
    val options = TableOptions.columns(columns.toJSArray).searchOnButton(false).filterControl(false)
    $(s"#${modalId} #${tableId}").bootstrapTable(options)
  }

  def registerEvent = {
    $(document.body).on("click", s"#js-just-qiandao", "", (y: Element) => {
      if (!$(y).hasClass("actived")) {
        signIn
      }
    })
    $("#js-qiandao-history").on("click", () => {
      signInInfoShow
    })
    $("#js-qiandao-list").on("click", "li", "", (y: Element) => {
      if ($(y).hasClass("able-qiandao")) {
        signIn
      }
    })
  }

  def signInInfoShow = {
    val url = g.jsRoutes.controllers.UserController.getHasSignInInfo().url.toString
    Ajax.get(url = s"${url.noCache}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val rs = xhr.responseText.toJDJAn
      val tableData = rs.map { case (k, v) =>
        val days = v.toJArI
        days.map { day =>
          js.Dictionary("time" -> s"${k}.${day}", "reward" -> 100, "explain" -> messages("reward"))
        }
      }.flatten.toJSArray
      $(s"#${tableId}").bootstrapTable("load", tableData)

      val totalNum = tableData.size
      $("#totalNum").text(s"${totalNum}")
      $("#signInCoin").text(s"${100 * totalNum}")

      $(s"#${modalId}").modal("show")
    }
  }

  def refreshCalendar = {
    val dateBox = $("#js-qiandao-list")
    val currentDate = $(".current-date")
    val myDate = new Date()
    val dateStr = s"${myDate.getFullYear()}-${myDate.getMonth() + 1}-${myDate.getDate()}"
    currentDate.text(dateStr)
    val d = new Date(myDate.getFullYear().toInt, myDate.getMonth().toInt + 1, 0)
    val totalDay = d.getDate().toInt
    val html = (1 to 42).map { i =>
      li(
        div(`class` := "qiandao-icon")
      )
    }.mkString("")
    dateBox.html(html)
    val dateLi = dateBox.find("li")
    (1 to totalDay).foreach { i =>
      dateLi.eq(i + monthFirst - 1).addClass(s"date${i}")
    }
    $(".date" + myDate.getDate()).addClass("able-qiandao")
  }

  def refreshHasSignIn = {
    val dateBox = $("#js-qiandao-list")
    val url = g.jsRoutes.controllers.UserController.getHasSignInCurMonth().url.toString
    Ajax.get(url = s"${url.noCache}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val dateArray = xhr.responseText.toJArI
      val dateLi = dateBox.find("li")
      dateArray.foreach { j =>
        dateLi.eq(j + monthFirst - 1).addClass("qiandao")
        if (j == myDate.getDate()) {
          $("#js-just-qiandao").addClass("actived")
          $(".date" + myDate.getDate()).removeClass("able-qiandao")
        }
      }
      $("#signInNum").text(dateArray.size.toString)
    }
  }

  def signIn = {
    val url = g.jsRoutes.controllers.UserController.signIn().url.toString
    Ajax.get(url = s"${url.noCache}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      refreshHasSignIn.zip(Header.init).map { x =>
        $("#coin").levelup("increment", 100)
        layer.msg(messages("signedIn"), LayerOptions.icon(1).time(2000))
      }
    }
  }

  def refreshCoin = {
    val url = g.jsRoutes.controllers.UserController.getCoin().url.toString
    Ajax.get(url = s"${url.noCache}", headers = Map("Content-Type" -> "application/json")).map { xhr =>
      val coin = xhr.responseText.toInt
      $("#coin").levelup(LevelUpOptions.start(coin).value(coin))
    }
  }

}
